import React from 'react';
import { Card, Row, Col, Space, Button, message } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import EditForm from './components/EditForm';
import { add, update, detail } from '@/services/Role';
import {history} from 'umi';

class Detail extends React.Component {

  constructor(props) {
    super(props);
    this.id = props.location.query.id;
    this.formRef = React.createRef();
    this.state = {isLoading: false};
  }

  /* 获取详情 */
  getDetail = async () => {
    try {
      const id = this.id;
      const {setFieldsValue} = this.formRef.current;
      const res = await detail(id);
      const {name, isInner, describe} = res;
      setFieldsValue({
        name,
        isInner,
        describe
      })
    } catch (e) {
      console.error('role.edit', e);
    }
  }

  /* 重置 */
  onReset = () => {
    const {resetFields} = this.formRef.current;
    resetFields();
  }

  /* 确认 */
  onConfirm = async () => {
    try {
      const id = this.id;
      const props = this.props;
      const {validateFields} = this.formRef.current;
      const values = await validateFields();
      this.setState({isLoading: true});
      id ? await update({...values, id}) : await add({...values});
      message.success('编辑成功！');
      props.update ? props.update() : null;
      setTimeout(function() {history.goBack()}, 1500)
    } catch (e) {
      console.error('role.edit', e);
      e.message ? message.error(e.message) : null;
    } finally {
      this.setState({isLoading: false});
    }
  }

  componentDidMount () {
    const id = this.id;
    id ? this.getDetail() : null;
  }

  render() {
    const {onConfirm, onReset, id, formRef } = this;
    const isLoading = this.state.isLoading;
    return (
      <PageContainer>
        <Card
          title={id ? '修改' : '新增'}
          bodyStyle={{ paddingTop: 48, paddingBottom: 48 }}
          bordered={false}>
          <div style={{ width: '70vw' }}>
            <EditForm ref={formRef} />
            <Row>
              <Col span={6}></Col>
              <Col span={6}>
                <Space>
                  <Button onClick={() => {history.goBack()}}>取消</Button>
                  <Button onClick={onReset}>重置</Button>
                  <Button loading={isLoading} type="primary" onClick={onConfirm}>确定</Button>
                </Space>
              </Col>
            </Row>
          </div>
        </Card>
      </PageContainer>
    );
  }
}

export default Detail;
